extends Node2D

@onready var card_node: Node2D = $table/cardNode
@onready var name_anim_player: AnimationPlayer = $UI/nameAnimPlayer
@onready var audio_stream_player_2: AudioStreamPlayer = $AudioStreamPlayer2
@onready var noble_node: Node2D = $table/nobleNode

const CARD = preload("res://scenes/card/card.tscn")
var cardOnTable = []


# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	GameManager.card_on_deck_node = deck_card
	GameManager.set_card_signal.connect(set_card)
	GameManager.player_turn_start.connect(start_player_turn)
	GameManager.update_opt_button.connect(update_btn)
	GameManager.set_a_card.connect(set_a_card)
	GameManager.show_save_card_signal.connect(showSaveCardDlg)
	GameManager.get_noble_card.connect(get_noble_card)
	GameManager.game_end_signal.connect(game_end)
	GameManager.player_get_gem_anim.connect(player_get_gem_anim)
	for item in card_node.get_children():
		cardOnTable.push_back(item)
	pass # Replace with function body.

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass

func _on_start_button_pressed() -> void:
	print('开始游戏')
	GameManager.setup_game(2)
	set_noble_card()
	pass # Replace with function body.

func set_card(data):
	var pos = cardOnTable[data.position].position
	var card_instance = CARD.instantiate()
	deck_card.add_child(card_instance)
	card_instance.initialize(data.card,data.position)
	card_instance.position = pos
	
@onready var noble_card: Node2D = $table/nobleCard
func set_noble_card():
	for i in range(3):
		var card_res = GameManager.noble_cards[i]
		var card_instance = CARD.instantiate()
		noble_card.add_child(card_instance)
		card_instance.initialize(card_res,13)
		var pos = noble_node.get_children()[i].position
		card_instance.position = pos
		
func get_noble_card(data):
	var p_position = [
		[354,354],
		[1434,354]
	]
	var current_player = GameManager.current_player
	for card in noble_card.get_children():
		if card.card_info.card_id == data.card_id:
			var tween = get_tree().create_tween()
			tween.tween_property(card, "position", Vector2(p_position[current_player][0],p_position[current_player][1]), 0.3)
			await tween.finished
			card.queue_free()
	
@onready var deck_card: Node2D = $deckCard
func set_a_card(data):
	var card_res
	if data < 4:
		card_res = GameManager.unused_cards[1].pop_back()
		GameManager.revealed_cards[1].append(card_res)
	elif  data <8:
		card_res = GameManager.unused_cards[2].pop_back()
		GameManager.revealed_cards[2].append(card_res)
	else:
		card_res = GameManager.unused_cards[3].pop_back()
		GameManager.revealed_cards[3].append(card_res)
	var card_instance = CARD.instantiate()
	deck_card.add_child(card_instance)
	card_instance.initialize(card_res,data)
	var pos = cardOnTable[data].position
	card_instance.position = pos
	
@onready var h_box_container: HBoxContainer = $UI/HBoxContainer
func start_player_turn(player:int):
	update_card_help_info()
	GameManager.select_card = null
	for item in h_box_container.get_children():
		item.hide()
	if player == 0:
		name_anim_player.play('playering')
	if player == 1:
		name_anim_player.play('aiing')
		var re =  aiDecision.make_decision()
		await get_tree().create_timer(2).timeout
		print('ai' ,re)
		match re.type:
			'take_gems':
				GameManager.players[1].save_coin = re.gems
				GameManager.handle_player_action(0,GameManager.players[1])
			'purchase':
				for item in deck_card.get_children():
					if item.card_info.card_id == re.card.card_id:
						GameManager.select_card = item
				GameManager.player_buy_card(GameManager.players[1], GameManager.select_card)
				
func update_card_help_info():
	for item in deck_card.get_children():
		item.close_anim()
		if GameManager.current_player == 0 && ruleSystem.can_purchase_card(GameManager.players[0],item.card_info):
			item.can_buy()

func _on_endturn_button_pressed() -> void:
	GameManager.start_player_turn( abs(GameManager.current_player - 1) )
	
@onready var button: Button = $UI/HBoxContainer/Button
@onready var button_2: Button = $UI/HBoxContainer/Button2
@onready var button_3: Button = $UI/HBoxContainer/Button3
func update_btn():
	button.hide()
	button_2.hide()
	button_3.hide()
	for item in GameManager.players[0].save_coin:
		if item > 0:
			button.show()
	if GameManager.select_card:
		button_2.show()
		button_3.show()
	
func playerGetGem() -> void:
	GameManager.handle_player_action(0,GameManager.players[0])

func save_card() -> void:
	if !GameManager.select_card:
		return
	# 检查合法性
	if GameManager.select_card.idx < 0:
		return
	var c_player = GameManager.players[GameManager.current_player]
	if c_player.reserved_cards.size() == 3:
		return
	if GameManager.available_gems[5] > 0:
		var total = 0
		for item in c_player.gems:
			total += c_player.gems[item]
		if total < 10:
			GameManager.available_gems[5] -= 1
			c_player.gems[5] += 1
	c_player.reserved_cards.push_back(GameManager.select_card.card_info)
	save_card_scene(GameManager.select_card.card_info)
	var idx = GameManager.select_card.idx
	GameManager.update_coin_signal.emit()
	GameManager.select_card.queue_free()
	await get_tree().create_timer(1.5).timeout
	GameManager.set_a_card.emit(idx)
	GameManager.start_player_turn( abs(GameManager.current_player - 1) )
	

func buy_card() -> void:
	if !GameManager.select_card:
		return
	var c_player = GameManager.players[GameManager.current_player]
	if !ruleSystem.can_purchase_card(c_player, GameManager.select_card.card_info):
		return
	GameManager.player_buy_card(c_player, GameManager.select_card)
	
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var sprite_2d: Sprite2D = $saveCard/Sprite2D
@onready var sprite_2d_2: Sprite2D = $saveCard/Sprite2D2
@onready var sprite_2d_3: Sprite2D = $saveCard/Sprite2D3
@onready var node_2d: Node2D = $saveCard/Node2D

func showSaveCardDlg():
	animation_player.play('showDlg')

func return_main() -> void:
	animation_player.play('return')

func save_card_scene(card:CardData):
	var card_instance = CARD.instantiate()
	card_instance.initialize(card,-1)
	node_2d.add_child(card_instance)
	var li = [sprite_2d,sprite_2d_2,sprite_2d_3]
	for i in GameManager.players[0].reserved_cards.size():
		node_2d.get_children()[i].position = li[i].position


func _on_button_pressed() -> void:
	GameManager.setup_game(2)
	
@onready var panel: Panel = $UI/Panel
func game_end():
	panel.show()
	name_anim_player.play('game_end')


var gem_res = [
	preload("res://assets/img/white_coin.png"),
	preload("res://assets/img/blue_coin.png"),
	preload("res://assets/img/red_coin.png"),
	preload("res://assets/img/green_coin.png"),
	preload("res://assets/img/brown_coin.png"),
	preload("res://assets/img/gold_coin.png"),
]
@onready var chip_node: Node2D = $table/chipNode

func player_get_gem_anim():
	var c_player:PlayerState = GameManager.players[GameManager.current_player]
	var temp = []
	for item in range(6):
		if c_player.save_coin[item] > 0:
			var gem = Sprite2D.new()
			gem.texture = gem_res[item]
			gem.position = chip_node.get_children()[item].global_position
			add_child(gem)
			var tween = get_tree().create_tween()
			tween.tween_property(gem, "position", Vector2(GameManager.p_position[GameManager.current_player][0],GameManager.p_position[GameManager.current_player][1]), 0.3)
			temp.push_back(gem)
			tween.tween_callback(gem.queue_free)
	
